﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp_Property
{
    public class PropertyDemo:Control
    {
        public static readonly DependencyProperty AgeProperty;

        static PropertyDemo()
        {
            AgeProperty = DependencyProperty.Register(
                "Age",
                typeof(int),
                typeof(PropertyDemo),new PropertyMetadata(
                    10, 
                    new PropertyChangedCallback(AgePropertyChange), 
                    new CoerceValueCallback(AgeCoerceValue)),
                new ValidateValueCallback(AgeValidateValue));
        }


        public int Age
        {
            get { return (int)this.GetValue(AgeProperty); }
            set { this.SetValue(AgeProperty, value);}
        }

        public PropertyDemo()
        {
            this.Loaded += (object sender, RoutedEventArgs e) => 
            {
                //this.Age = 40;
                //this.SetValue(AgeProperty, 100);
                //this.Age = -1;
                this.Age = 161;
            };
        }

        /// <summary>
        /// 监听值变化
        /// </summary>
        /// <param name="dependencyObject"></param>
        /// <param name="e"></param>
        static void AgePropertyChange(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            Console.WriteLine(e.OldValue);
            Console.WriteLine(e.NewValue);
        }

        /// <summary>
        /// 监听值是是否有效
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        static bool AgeValidateValue(Object value) 
        {
            //int _age = (int)value;
            //if(_age <= 0 || _age>=160)
            //    return false;
            return true;
        }

        /// <summary>
        /// 当值不符合条件时候，强制复制成一下值
        /// </summary>
        /// <param name="dependencyObject"></param>
        /// <param name="baseValue"></param>
        /// <returns></returns>
        static object AgeCoerceValue(DependencyObject dependencyObject, Object baseValue)
        {
            int _age = (int)baseValue;
            if (_age <= 0) return 1;
            if (_age >= 160) return 159;
            return baseValue;
        }


      
    }
}
